package com.etc.controller;

import com.etc.entity.EMP;
import com.etc.service.EmpService;
import com.etc.util.QueryResponseData;
import com.etc.util.ResponseData;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class EmpController {

    @Autowired
    private EmpService service;
    @Autowired
    private QueryResponseData queryResponseData;
    @Autowired
    private ResponseData responseData;

    /**
     * 根据关键字分页查询
     * @param keywords  关键字
     * @param pageNo    页码
     * @param pageSize  每页记录数
     * @return
     */
    @GetMapping("querybypage")
    public QueryResponseData<EMP> queryBypage(@RequestParam(value = "keywords",defaultValue = "",required = false)String keywords, @RequestParam(value = "page",defaultValue = "1",required = false)int pageNo,@RequestParam(value = "limit",defaultValue = "10",required = false)int pageSize){
        PageHelper.startPage(pageNo,pageSize);
        List<EMP> emps = service.selectByPage(keywords);
        PageInfo<EMP> info = new PageInfo<>(emps);
        queryResponseData.setCount(info.getTotal());
        queryResponseData.setData(emps);
        return queryResponseData;
    }

    /**
     * 根据empno删除记录
     * @param empno 员工编号
     * @return
     */
    @DeleteMapping("delete")
    public ResponseData delete(@RequestParam int empno){
        int result = service.deleteByPrimaryKey((short) empno);
        if (result == 0){
            responseData.setMsg("faild");
            return responseData;
        }
        return responseData;
    }

    /**
     * 修改记录
     * @param emp   员工对象
     * @return
     */
    @PutMapping("update")
    public ResponseData update(@RequestBody EMP emp){
        int result = service.updateByPrimaryKeySelective(emp);
        if (result == 0){
            responseData.setMsg("faild");
            return responseData;
        }
        return responseData;
    }

    /**
     * 增加记录
     * @param emp   员工对象
     * @return
     */
    @PostMapping("add")
    public ResponseData add(@RequestBody EMP emp){
        int result = service.insert(emp);
        if (result == 0){
            responseData.setMsg("faild");
            return responseData;
        }
        return responseData;
    }
}
